//
//  SearchViewController.swift
//  clreader
//
//  Created by colin on 2019/3/27.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

/// 搜索界面
class SearchViewController: CLBaseViewController {

    private lazy var tagsTableView = UITableView(frame: CGRect.zero, style: .plain)
    private var resultViewController:SearchResultViewController?
    private var searchBar:SearchBar?
    private lazy var cellHeights = [IndexPath:CGFloat]()
    private lazy var hotKeys = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        let topBar = UIView().then {
            let buttonCancel = UIButton(type: .custom).then {
                $0.setTitle("取消", for: .normal)
                $0.setTitleColor(UIColor(hex: "B93624"), for: .normal)
                $0.titleLabel?.font = UIFont.systemFont(ofSize: 15.0, weight: .light)
                $0.addTarget(self, action: #selector(self.actionCancel(_:)), for: .touchUpInside)
            }
            $0.addSubview(buttonCancel)
            buttonCancel.snp.makeConstraints({ (make) in
                make.right.top.bottom.equalToSuperview()
                make.width.equalTo(55.0)
            })
            
            let searchBar = SearchBar(valueChanged: { [weak self] (key) in
                if key.isEmpty {
                    self?.resultViewController?.removeFromParent()
                    self?.resultViewController?.view.removeFromSuperview()
                    self?.resultViewController = nil
                }
            }, searchHandle: { [weak self] (key) in
                if !key.isEmpty {
                    self?.search(keyword: key)
                }
            })
            $0.addSubview(searchBar)
            searchBar.snp.makeConstraints({ (make) in
                make.left.equalToSuperview().offset(15.0)
                make.centerY.equalToSuperview()
                make.right.equalTo(buttonCancel.snp.left)
            })
            self.searchBar = searchBar
            
            let line = UIView()
            line.backgroundColor = UIColor(hex: "EFEFEF")
            $0.addSubview(line)
            line.snp.makeConstraints({ (make) in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(0.5)
            })
            
        }
        self.view.addSubview(topBar)
        topBar.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.height.equalTo(44.0)
        }

        self.tagsTableView.do {
            $0.register(CellTag.self, forCellReuseIdentifier: CellTag.reuseId)
            $0.dataSource = self
            $0.delegate = self
            
            $0.contentInsetAdjustmentBehavior = .never
            $0.backgroundColor = UIColor.white
            $0.separatorStyle = .none
            $0.estimatedSectionHeaderHeight = CGFloat.leastNormalMagnitude
            $0.sectionHeaderHeight = CGFloat.leastNormalMagnitude
            $0.estimatedSectionFooterHeight = CGFloat.leastNormalMagnitude
            $0.sectionFooterHeight = CGFloat.leastNormalMagnitude
            $0.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
        }
        
        self.view.addSubview(self.tagsTableView)
        self.tagsTableView.snp.makeConstraints { (make) in
            make.top.equalTo(topBar.snp.bottom)
            make.left.right.equalToSuperview()
            make.bottom.equalTo(self.view.safeAreaLayoutGuide.snp.bottom)
        }
        
        self.loadHotKeys()
    }
    
}

extension SearchViewController {
    
    /// 搜索
    private func search(keyword:String) {
        if let controller = self.resultViewController {
            controller.keyword = keyword
        } else {
            let controller = SearchResultViewController(keyword: keyword)
            self.view.addSubview(controller.view)
            controller.view.snp.makeConstraints { (make) in
                make.edges.equalTo(self.tagsTableView)
            }
            self.addChild(controller)
            controller.didMove(toParent: self)
            self.resultViewController = controller
        }
    }
    
}

extension SearchViewController {
    private func loadHotKeys() {
        _ = Router.hotKeys.request { [weak self] (response:RequestResponse<[String]>) in
            if case .success(let res,_) = response {
                if let hotKeys_ = res {
                    self?.hotKeys = hotKeys_
                    self?.tagsTableView.reloadData()
                }
            }
        }
    }
}

extension SearchViewController : UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CellTag.reuseId) as! CellTag
        if indexPath.row == 0 {
            cell.refresh(type: .hotkey, tags: self.hotKeys, searchHandle: { [weak self] (key) in
                self?.searchBar?.text = key
                self?.search(keyword: key)
            })
        } else {
            cell.refresh(type: .history, tags: [] , searchHandle:  { [weak self] (key) in
                self?.searchBar?.text = key
                self?.search(keyword: key)
            }, clearHandle: { [weak self] in
                print("222")
            })
        }
        self.cellHeights[indexPath] = cell.cellHeight
        return cell
    }
}

extension SearchViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if let cellHeight = self.cellHeights[indexPath] {
            return cellHeight
        } else {
            return 0
        }
    }
}

extension SearchViewController {
    @objc private func actionCancel(_ sender:Any) {
        self.navigationController?.popViewController(animated: true)
    }
}

extension SearchViewController {
    
    class SearchBar: UIView {
        
        var text = "" {
            didSet {
                self.textField.text = self.text
            }
        }
        
        private var valueChanged:((_ value:String)->Void)?
        private var searchHandle:((_ value:String)->Void)?
        private lazy var textField = UITextField(frame: CGRect.zero)

        init(valueChanged:((_ value:String)->Void)?,searchHandle:((_ value:String)->Void)?) {
            super.init(frame: CGRect.zero)
            self.valueChanged = valueChanged
            self.searchHandle = searchHandle
            self.initViews()
        }
        
        func initViews() {
            self.backgroundColor = UIColor.white
            let container = UIView().then {
                $0.backgroundColor = UIColor(hex: "EFEFEF")
                $0.layer.cornerRadius = 17.5
                $0.layer.masksToBounds = true
                
                // 图片
                let imageViewIcon = UIImageView(image: UIImage(named: "icon_search"))
                $0.addSubview(imageViewIcon)
                imageViewIcon.snp.makeConstraints({ (make) in
                    make.left.equalToSuperview().offset(15.0)
                    make.size.equalTo(CGSize(width: 16.0, height: 16.0))
                    make.centerY.equalToSuperview()
                })
                
                self.textField.do {
                    $0.addRightButtonOnKeyboardWithText("搜索", target: self, action: #selector(self.actionSearch(_:)))
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
                    $0.returnKeyType = .search
                    $0.clearButtonMode = .always
                    $0.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
                    $0.delegate = self
                }
                $0.addSubview(self.textField)
                self.textField.snp.makeConstraints({ (make) in
                    make.top.bottom.equalToSuperview()
                    make.right.equalToSuperview().offset(-15.0)
                    make.left.equalTo(imageViewIcon.snp.right).offset(15.0)
                })
                
            }
            self.addSubview(container)
            container.snp.makeConstraints { (make) in
                make.height.equalTo(35.0)
                make.edges.equalToSuperview()
            }
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
    
}

extension SearchViewController.SearchBar : UITextFieldDelegate {
    
    @objc private func actionSearch(_ sender:Any) {
        var key = ""
        if let text = self.textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) {
            key = text
        }
        self.searchHandle?(key)
    }
    
    @objc private func textChanged(_ sender:UITextField?) {
        var key = ""
        if let text = sender?.text?.trimmingCharacters(in: .whitespacesAndNewlines) {
            key = text
        }
        self.valueChanged?(key)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField.returnKeyType == .search {
            var key = ""
            if let text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines) {
                key = text
            }
            self.searchHandle?(key)
        }
        return true
    }
}
